package com.ruoyi.project.platform.controller;

import java.util.List;
import java.util.UUID;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.platform.agent.ContainerAgent;
import com.ruoyi.project.platform.agent.basic.AccountDto;
import com.ruoyi.project.platform.agent.basic.RestClientWrapper;
import com.ruoyi.project.platform.agent.basic.TriggerDto;
import com.ruoyi.project.platform.agent.constant.Platform;
import com.ruoyi.project.platform.dto.RunningContainerDto;
import com.ruoyi.project.platform.dto.UserRunningDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.platform.domain.RRobotRunning;
import com.ruoyi.project.platform.service.IRRobotRunningService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 机器人实例Controller
 *
 * @author ruoyi
 * @date 2020-07-29
 */
@Api("机器人实例")
@RestController
@RequestMapping("/platform/running")
public class RRobotRunningController extends BaseController {
    @Autowired
    private IRRobotRunningService rRobotRunningService;
    @Autowired
    private ContainerAgent containerAgent;

    /**
     * 查询机器人实例列表
     */
    @PreAuthorize("@ss.hasPermi('platform:running:list')")
    @GetMapping("/list")
    public TableDataInfo list(RRobotRunning rRobotRunning) {
        startPage();
        List<RRobotRunning> list = rRobotRunningService.selectRRobotRunningList(rRobotRunning);
        if (!list.isEmpty()) {
            list.forEach(m -> {
                tempUpdate(m);
            });
        }
        return getDataTable(list);
    }

    private void tempUpdate(RRobotRunning r) {
        Boolean isNeedUpdate = false;
        if (StringUtils.isEmpty(r.getPltKey())) {
            isNeedUpdate = true;
            r.setPltKey(UUID.randomUUID().toString());
        }

        if (StringUtils.isEmpty(r.getPltSecret())) {
            isNeedUpdate = true;
            r.setPltSecret(UUID.randomUUID().toString());
        }

        if (isNeedUpdate) {
            rRobotRunningService.updateRRobotRunning(r);
        }
    }

    /**
     * 导出机器人实例列表
     */
    @PreAuthorize("@ss.hasPermi('platform:running:export')")
    @Log(title = "机器人实例", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(RRobotRunning rRobotRunning) {
        List<RRobotRunning> list = rRobotRunningService.selectRRobotRunningList(rRobotRunning);
        ExcelUtil<RRobotRunning> util = new ExcelUtil<RRobotRunning>(RRobotRunning.class);
        return util.exportExcel(list, "running");
    }

    /**
     * 获取机器人实例详细信息
     */
    @PreAuthorize("@ss.hasPermi('platform:running:query')")
    @GetMapping(value = "/{runningId}")
    public AjaxResult getInfo(@PathVariable("runningId") Long runningId) {
        return AjaxResult.success(rRobotRunningService.selectRRobotRunningById(runningId));
    }

    /**
     * 新增机器人实例
     */
    @PreAuthorize("@ss.hasPermi('platform:running:add')")
    @Log(title = "机器人实例", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RRobotRunning rRobotRunning) {
        return toAjax(rRobotRunningService.insertRRobotRunning(rRobotRunning));
    }

    /**
     * 修改机器人实例
     */
    @PreAuthorize("@ss.hasPermi('platform:running:edit')")
    @Log(title = "机器人实例", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RRobotRunning rRobotRunning) {
        return toAjax(rRobotRunningService.updateRRobotRunning(rRobotRunning));
    }

    /**
     * 删除机器人实例
     */
    @PreAuthorize("@ss.hasPermi('platform:running:remove')")
    @Log(title = "机器人实例", businessType = BusinessType.DELETE)
    @DeleteMapping("/{runningIds}")
    public AjaxResult remove(@PathVariable Long[] runningIds) {
        return toAjax(rRobotRunningService.deleteRRobotRunningByIds(runningIds));
    }

    /**
     * 查询机器人实例
     */
    @PreAuthorize("@ss.hasPermi('platform:running:list')")
    @GetMapping("/queryByIds")
    public AjaxResult queryByIds(@RequestParam Long[] runningIds) {
        return AjaxResult.success(rRobotRunningService.getRuningByIds(runningIds));
    }

    /**
     * 可用资源
     */
    @PreAuthorize("@ss.hasPermi('platform:running:list')")
    @GetMapping("/resources/{userId}")
    public @ResponseBody
    UserRunningDto.UserResource resources(@PathVariable Long userId) {
        return rRobotRunningService.resourcesByUserId(userId);
    }

    @PreAuthorize("@ss.hasPermi('platform:running:list')")
    @GetMapping("/resources")
    public @ResponseBody
    UserRunningDto.UserResource resources() {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        return rRobotRunningService.resourcesByUserId(userId);
    }

    /**
     * 节点查询
     */
    @PreAuthorize("@ss.hasPermi('platform:running:list')")
    @GetMapping("/endpoints")
    public @ResponseBody
    AjaxResult endpoints() {
        return AjaxResult.success(containerAgent.endpoints());
    }


    /**
     * 节点创建
     */
    @PreAuthorize("@ss.hasPermi('platform:running:edit')")
    @PutMapping("/containers/create")
    public @ResponseBody
    AjaxResult create(@RequestParam Long endpointId, @RequestParam Long runningId) {
        return AjaxResult.success(rRobotRunningService.create(endpointId, runningId));
    }

    /**
     * 停止
     */
    @PreAuthorize("@ss.hasPermi('platform:running:edit')")
    @PutMapping("/running/{runningId}/stop")
    public @ResponseBody
    AjaxResult stop(@PathVariable Long runningId) {
        return AjaxResult.success(rRobotRunningService.stop(runningId));
    }

    /**
     * 停止
     */
    @PreAuthorize("@ss.hasPermi('platform:running:edit')")
    @PutMapping("/running/{runningId}/update_version")
    public @ResponseBody
    AjaxResult updateVersion(@PathVariable Long runningId) {
        return AjaxResult.success(rRobotRunningService.updateVersion(runningId));
    }

    /**
     * 查询
     */
    @PreAuthorize("@ss.hasPermi('platform:running:list')")
    @GetMapping("/running/{runningId}/inspect")
    public @ResponseBody
    AjaxResult inspect(@PathVariable Long runningId) {
        return AjaxResult.success(rRobotRunningService.inspect(runningId));
    }

    /**
     * 启动
     */
    @PreAuthorize("@ss.hasPermi('platform:running:edit')")
    @PutMapping("/running/{runningId}/start")
    public @ResponseBody
    AjaxResult start(@PathVariable Long runningId) {
        return AjaxResult.success(rRobotRunningService.start(runningId));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('platform:running:edit')")
    @PutMapping("/running/{runningId}/remove")
    public @ResponseBody
    AjaxResult remove(@PathVariable Long runningId) {
        return AjaxResult.success(rRobotRunningService.remove(runningId));
    }

    /**
     * 重启
     */
    @PreAuthorize("@ss.hasPermi('platform:running:edit')")
    @PutMapping("/running/{runningId}/restart")
    public @ResponseBody
    AjaxResult restart(@PathVariable Long runningId) {
        return AjaxResult.success(rRobotRunningService.restart(runningId));
    }

    /**
     * 暂停
     */
    @PreAuthorize("@ss.hasPermi('platform:running:edit')")
    @PutMapping("/running/{runningId}/pause")
    public @ResponseBody
    AjaxResult pause(@PathVariable Long runningId) {
        return AjaxResult.success(rRobotRunningService.pause(runningId));
    }

    /**
     * 恢复
     */
    @PreAuthorize("@ss.hasPermi('platform:running:edit')")
    @PutMapping("/running/{runningId}/reverse")
    public @ResponseBody
    AjaxResult reverse(@PathVariable Long runningId) {
        return AjaxResult.success(rRobotRunningService.reverse(runningId));
    }

    /**
     * exchanges
     */
    @ApiOperation("查看交易所信息")
    @GetMapping("/containers/{containerId}/exchanges")
    public @ResponseBody
    AjaxResult exchanges(@PathVariable String containerId) {
        return AjaxResult.success(rRobotRunningService.exchanges(containerId));
    }

    /**
     * mappings
     */
    @ApiOperation("查看交易参数")
    @GetMapping("/containers/{containerId}/mappings")
    public @ResponseBody
    AjaxResult mappings(@PathVariable String containerId) {
        return AjaxResult.success(rRobotRunningService.mappings(containerId));
    }

    /**
     * mappings
     */
    @ApiOperation("key验证")
    @PostMapping("/containers/verify")
    public @ResponseBody
    AjaxResult mappings(@RequestBody RunningContainerDto.VerifyBase verify) {
        return AjaxResult.success(rRobotRunningService.verify(verify));
    }


    /********************************账户信息******************************************/
    @ApiOperation(value = "当前资产")
    @GetMapping("/containers/{runningId}/current")
    public AjaxResult current(@PathVariable String runningId, @RequestParam Platform platform) {
        return AjaxResult.success(rRobotRunningService.getCurrentBalance(runningId, platform));
    }

    @ApiOperation(value = "账户报表历史")
    @GetMapping("/containers/{runningId}/report")
    public AjaxResult report(@PathVariable String runningId, @RequestParam Platform platform) {
        return AjaxResult.success(rRobotRunningService.getAccountReport(runningId, platform));
    }

    @ApiOperation(value = "平均成本")
    @GetMapping("/containers/{runningId}/avg")
    public AjaxResult report(@PathVariable String runningId, @RequestParam Platform platform, @RequestParam Long start) {
        return AjaxResult.success(rRobotRunningService.getAvgDealPrice(runningId, platform, start));
    }

    @ApiOperation(value = "盘口深度分析")
    @GetMapping("/containers/{runningId}/analyseDepths")
    public AjaxResult analyseDepths(@PathVariable String runningId, @RequestParam Platform platform) {
        return AjaxResult.success(rRobotRunningService.analyseDepths(runningId, platform));
    }

    @ApiOperation(value = "资金监控")
    @GetMapping("/containers/{runningId}/usdtCurrent")
    public AjaxResult usdtCurrent(@PathVariable String runningId, @RequestParam Platform platform, @RequestParam Long start) {
        return AjaxResult.success(rRobotRunningService.usdtCurrent(runningId, platform, start));
    }


    /********************************交易所中转******************************************/
    @ApiOperation(value = "ticker")
    @GetMapping("/containers/{runningId}/ticker")
    public AjaxResult ticker(@PathVariable String runningId, @RequestParam Platform platform) {
        return AjaxResult.success(rRobotRunningService.getTicker(runningId, platform));
    }


    @ApiOperation(value = "queryFlyOrders")
    @GetMapping("/containers/{runningId}/queryFlyOrders")
    public AjaxResult queryFlyOrders(@PathVariable String runningId, @RequestParam Platform platform, @RequestParam Integer type) {
        return AjaxResult.success(rRobotRunningService.queryFlyOrders(runningId, platform, type));
    }


    @ApiOperation(value = "getDealedOrder")
    @GetMapping("/containers/{runningId}/getDealedOrder")
    public AjaxResult getDealedOrder(@PathVariable String runningId, @RequestParam Platform platform, @RequestParam Integer type,
                                     @RequestParam Long size, @RequestParam Long page, @RequestParam Long start, @RequestParam Long end) {
        return AjaxResult.success(rRobotRunningService.getDealedOrder(runningId, platform, type, start, end, size, page));
    }


    @ApiOperation(value = "限价控盘")
    @PostMapping("/containers/{runningId}/placeOrder")
    public AjaxResult placeOrder(@PathVariable String runningId, @RequestBody AccountDto.FixedAction action) {
        return AjaxResult.success(rRobotRunningService.placeOrder(runningId, action));
    }


    @ApiOperation(value = "限价订单撤单")
    @DeleteMapping("/containers/{runningId}/cancelOrder")
    public AjaxResult cancelOrder(@PathVariable String runningId, @RequestParam Platform platform, @RequestParam Integer type,
                                  @RequestParam String orderId) {
        return AjaxResult.success(rRobotRunningService.cancelOrder(runningId, orderId, platform, type));
    }

    /********************************第三方机器人协调******************************************/


    @ApiOperation(value = "安全停止K线")
    @GetMapping("/containers/{runningId}/safe_stop")
    public AjaxResult safeStop(@PathVariable String runningId, @RequestParam Platform platform, @RequestParam(defaultValue = "30", required = false) Integer delay) {
        return AjaxResult.success(rRobotRunningService.caclasSafeStop(runningId, platform, delay));
    }

    @ApiOperation(value = "配置控盘")
    @PostMapping("/containers/{runningId}/config_action")
    public AjaxResult configAction(@PathVariable String runningId, @RequestBody AccountDto.Action action) {
        return AjaxResult.success(rRobotRunningService.configAction(runningId, action));
    }

    /******** ************************计划委托******************************************/
    @ApiOperation(value = "创建计划委托")
    @PostMapping("/containers/{runningId}/trigger/create")
    public AjaxResult createTrigger(@PathVariable String runningId, @RequestBody TriggerDto.TriggerBase trigger) {
        return AjaxResult.success(rRobotRunningService.createTrigger(runningId, trigger));
    }

    @ApiOperation(value = "查询计划委托")
    @GetMapping("/containers/{runningId}/trigger/list")
    public AjaxResult listTrigger(@PathVariable String runningId) {
        return AjaxResult.success(rRobotRunningService.listTrigger(runningId));
    }

    @ApiOperation(value = "关闭计划委托")
    @GetMapping("/containers/{runningId}/trigger/close")
    public AjaxResult closeTrigger(@PathVariable String runningId, @RequestParam Long id) {
        return AjaxResult.success(rRobotRunningService.closeTrigger(runningId, id));
    }

    @ApiOperation(value = "关闭计划委托")
    @GetMapping("/containers/{runningId}/trigger/active")
    public AjaxResult activeTrigger(@PathVariable String runningId, @RequestParam Long id) {
        return AjaxResult.success(rRobotRunningService.activeTrigger(runningId, id));
    }

    @ApiOperation(value = "关闭计划委托")
    @GetMapping("/containers/{runningId}/trigger/fresh")
    public AjaxResult freshTrigger(@PathVariable String runningId, @RequestParam Long id) {
        return AjaxResult.success(rRobotRunningService.freshTrigger(runningId, id));
    }

    @ApiOperation(value = "关闭计划委托")
    @DeleteMapping("/containers/{runningId}/trigger/delete")
    public AjaxResult deleteTrigger(@PathVariable String runningId, @RequestParam Long id) {
        return AjaxResult.success(rRobotRunningService.deleteTrigger(runningId, id));
    }

    @ApiOperation(value = "关闭所有计划委托")
    @GetMapping("/containers/{runningId}/trigger/closeAll")
    public AjaxResult closeAll(@PathVariable String runningId) {
        return AjaxResult.success(rRobotRunningService.closeAll(runningId));
    }

    @ApiOperation(value = "刷新所以计划委托")
    @GetMapping("/containers/{runningId}/trigger/freshAll")
    public AjaxResult freshAll(@PathVariable String runningId) {
        return AjaxResult.success(rRobotRunningService.freshAll(runningId));
    }

    @ApiOperation(value = "激活计划委托")
    @GetMapping("/containers/{runningId}/trigger/activeAll")
    public AjaxResult activeAll(@PathVariable String runningId) {
        return AjaxResult.success(rRobotRunningService.activeAll(runningId));
    }

}
